import { groupBy } from "lodash";
//import { FieldNamesProps } from "@/components/common/ProTable/interface";

/**
 * @description 判断数据类型
 * @param {*} val 需要判断类型的数据
 * @returns {String}
 * Object.prototype.toString.call(val)   得到[object Object]或[object Array]
 */
export function isType(val: any) {
  if (val === null) return "null";
  if (typeof val !== "object") {
    return typeof val;
  } else {
    return Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase();
  }
}

/**
 * 判断是否为空
 * @param str
 * @returns
 */
export function isEmpty(str: any) {
  if ((typeof str == "string" && str == "") || str == null || str == undefined) {
    return true;
  }
  return false;
}

/**
 * @description 生成随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @returns {Number}
 */
export function randomNum(min: number, max: number): number {
  let num = Math.floor(Math.random() * (min - max) + max);
  return num;
}

/**
 * 判断是否存在子级
 * @param data is_leaf==1 无子级；is_leaf==2 有子级
 * @param pageInfo 分页信息
 * @returns
 */
export function appendHasChildren(data: any[], pageInfo?: any, isSearch = false) {
  if (data.length == 0) {
    return data;
  }
  let addSize = 0;
  if (pageInfo) {
    addSize = (pageInfo.current_page - 1) * pageInfo.page_size;
  }
  data.forEach((item, index) => {
    //查询不显示树形
    if (!isSearch) {
      item.hasChildren = item.is_leaf === 2;
    }
    item.pIndex = index + 1 + addSize;
  });
  return data;
}

/**
 * 时间戳转换为时间
 * @param timestamp 时间戳
 * @param format 格式化类型格式
 * @returns
 */
export function timestampToTime(timestamp: any, format?: string) {
  if (!timestamp) return "";
  timestamp = timestamp.length == 10 ? timestamp * 1000 : timestamp;
  const date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = date.getFullYear() + "-";
  const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  const D = (date.getDate() < 10 ? "0" : "") + date.getDate() + " ";
  const h = (date.getHours() < 10 ? "0" : "") + date.getHours() + ":";
  const m = (date.getMinutes() < 10 ? "0" : "") + date.getMinutes() + ":";
  const s = (date.getSeconds() < 10 ? "0" : "") + date.getSeconds();

  switch (format) {
    case "yyyy-MM-dd hh:mm:ss":
      return Y + M + D + h + m + s;
      break;
    default:
      return Y + M + D;
      break;
  }
}

/**
 * 金额格式化
 * @param cellVal 值
 * @returns
 */
export function formatMoney(cellVal: any, unit?: number | "million" | "billion") {
  let val = Number(cellVal);
  if (!isNaN(val)) {
    if (isType(unit) === "number") {
      val = val / Number(unit);
    } else if (isType(unit) === "string") {
      if (unit === "billion") {
        val = val / 100000000;
      } else {
        val = val / 10000;
      }
    }
    return val.toLocaleString("zh", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  } else {
    return cellVal;
  }
}

/**
 * 百分比
 * @param number
 * @param minimumFractionDigits
 * @param maximumFractionDigits
 * @returns
 */
export const percentFormat = (num: any, minDigit = 2) => {
  let data = Number(num);
  if (!isNaN(data)) {
    const formatter = new Intl.NumberFormat("zh-CN", {
      style: "percent",
      minimumFractionDigits: minDigit,
      maximumFractionDigits: 2,
    });
    return formatter.format(data);
  } else {
    return "0%";
  }
};

/**
 * 保留n位小数，返回number类型
 * @param num
 * @param precision
 * @returns
 */
export const numFormat = (num: any, precision = 2) => {
  let data = Number(num);
  if (!isNaN(data)) {
    return Math.round(data * Math.pow(10, precision)) / Math.pow(10, precision);
  } else {
    return 0;
  }
};

/**
 * get路径拼接
 * @param uri url路径
 * @param params 参数
 * @returns
 */
export const urlJoint = (uri: string, params: any) => {
  if (!params) return uri;
  const paramsArray: string[] = [];
  Object.keys(params).forEach((key) => paramsArray.push(`${key}=${params[key]}`));
  if (uri.search(/\?/) === -1) {
    uri += `?${paramsArray.join("&")}`;
  } else {
    uri += `&${paramsArray.join("&")}`;
  }
  return uri;
};

/**
 *
 * @param columns 列属性
 * @param opName 操作名称：delete|add
 * @param opProps 操作属性，删除时string[], add时prop[]
 * @param preAddProp 在哪个元素前增加
 */
export function resetColumns(columns: any[], opName: string, opProps: any[], preAddProp?: string) {
  opProps.forEach((el: any) => {
    if (opName == "delete") {
      let inx = columns.findIndex((co: any) => co.prop == el);
      if (inx > -1) {
        columns.splice(inx, 1);
      }
    } else {
      let inx = columns.findIndex((co: any) => co.prop == el.prop);
      if (inx == -1) {
        if (preAddProp == "last") {
          columns.push(el);
        } else {
          let addIndex = columns.findIndex((co: any) => co.prop == preAddProp);
          columns.splice(addIndex, 0, el);
        }
      }
    }
  });
  return columns;
}

/**
 * 表格头数据格式化
 * @param columns 后端返回表格头数据
 * @returns
 */
export function formatColumn(columns: any[]) {
  return columns.map((el) => {
    return {
      prop: el.column_code,
      label: el.column_name,
      width: 120,
      isMinWidth: true,
    };
  });
}

/**
 * 清除查询空值属性
 * @param params
 * @returns
 */
export function cleanEmptyParams(params: any) {
  for (let key in params) {
    if (isType(params[key]) != "boolean" && !params[key]) {
      delete params[key];
    }
  }
  return params;
}
/**
 * 级联选择的全部处理
 * @param params
 * @returns
 */
export function paramsDeal(params: any) {
  if (params == undefined) return params;
  for (let key in params) {
    if (params[key] === "undefined") {
      params[key] = undefined;
    }
  }
  return params;
}

/**
 * 格式化get参数
 * @param params
 */
export function formatQueryParams(params: any, deep = false) {
  let copyParams = { ...params };
  if (deep) {
    copyParams = JSON.parse(JSON.stringify(params)); //会过滤掉undefined
  }
  for (let key in params) {
    if (isType(params[key]) === "array") {
      copyParams[key] = params[key].join(",");
    }
  }
  return copyParams;
}

/**
 * 校验值是否有效
 * @param curV
 * @param arr
 * @param keyName
 * @returns
 */
export function checkValidVal(curV: any, arr: any[], keyName?: string) {
  let key = keyName ? keyName : "id";
  let idx = arr.findIndex((el: any) => el[key] == curV);
  if (idx == -1) {
    return false;
  } else {
    return true;
  }
}

/**
 * 数组转列表
 * @param tree
 * @param arr
 * @returns
 */
export const treeToList = (tree: any[], arr = [] as any[]) => {
  // 遍历tree数组
  // map() 对数组中的每一项运行给定函数，返回每次函数调用的结果组成的数组，返回就是数组，不考虑true或者false；
  tree.map((item: any) => {
    if (item.children) {
      arr.push(...treeToList(item.children));
      delete item.children;
    }
    arr.push(item);
  });
  return arr;
};

/**
 * 获取第一个子元素
 * @param arr
 * @returns
 */
export function getFirstLeafEle(arr: any[]) {
  const ele = arr[0];
  if (ele.children != null && ele.children.length > 0) {
    return getFirstLeafEle(ele.children as any[]);
  } else {
    return ele;
  }
}

/**
 *
 * @param tree 树形数组
 * @param keyName 修改的可以
 * @param type 修改类型： 1（转字符串）
 * @returns
 */
export function setTreeVal(tree: any[], keyName: string, type: number) {
  tree.forEach((ele: any) => {
    if (ele.children) {
      setTreeVal(ele.children, keyName, type);
    }
    if (type == 1) {
      ele[keyName] = ele[keyName] ? ele[keyName] + "" : ele.strId; //注：null不能用""代替，因为和清空冲突
    }
  });
  return tree;
}

export const getSummaries = (columns: any, data: any, calcColumns: string[], moneyColumns: string[], callBack?: any) => {
  //console.log(columns, data);
  const sums: string[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (!data) return (sums[index] = "");
    if (isNum(column.property, calcColumns, moneyColumns)) {
      const values = data.map((item: any) => Number(item[column.property]));
      const sumVal = values.reduce((prev: any, curr: any) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return Number(Number(prev) + Number(curr));
        } else {
          return prev;
        }
      }, 0);
      let tempVal = "";
      //金额显示处理
      if (isNum(column.property, calcColumns, moneyColumns, true)) {
        tempVal = formatMoney(sumVal);
      } else {
        tempVal = sumVal.toString();
      }
      if (callBack) {
        sums[index] = callBack(column.property, tempVal);
      } else {
        sums[index] = tempVal;
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
/**
 * 判断是否是金额  tl
 * @param str
 * @returns
 */
function isNum(str: string, calcColumns: string[], moneyColumns: string[], isAmt = false) {
  let amtArr = calcColumns;
  if (isAmt) {
    amtArr = moneyColumns;
  }
  let flag = false;
  amtArr.forEach((el: string) => {
    if (str && str == el) {
      flag = true;
    }
  });
  return flag;
}

/**
 * 文本框长度等于规则校验
 * @param rule 校验规则
 * @param value 值
 * @param callback 回调
 * @param equalObj 等于对象（len：输入等于长度，msg：必填提示信息）
 */
export const lenEqualRule = (rule: any, value: any, callback: any, equalObj: { len: number; msg: string }) => {
  if (!value) {
    callback(new Error(equalObj.msg));
  } else if (value.length == equalObj.len) {
    callback();
  } else {
    callback(new Error(`长度必须为${equalObj.len}位`));
  }
};

//padding,margin值处理
export const getPaddingOrMargin = (arr: number[]) => {
  let len = arr.length;
  let top = 0,
    bottom = 0,
    left = 0,
    right = 0;
  switch (len) {
    case 1:
      top = arr[0];
      bottom = arr[0];
      left = arr[0];
      right = arr[0];
      break;
    case 2:
      top = arr[0];
      bottom = arr[0];
      left = arr[1];
      right = arr[1];
      break;
    case 3:
      top = arr[0];
      bottom = arr[2];
      left = arr[1];
      right = arr[1];
      break;
    case 4:
      top = arr[0];
      bottom = arr[2];
      left = arr[3];
      right = arr[1];
      break;
  }
  return { top, bottom, left, right };
};

export const getIcon = (name: string) => {
  return new URL(`/src/assets/images/icon/${name}.png`, import.meta.url).href;
};
export const getImg = (name: string) => {
  return new URL(`/src/assets/images/${name}`, import.meta.url).href;
};

/**
 * 获取指定年度的后几年数据
 * @param after
 * @param year 指定年度，默认当年
 */
export const getTargetAfterYear = (after: number = 5, year: number | string = new Date().getFullYear()) => {
  const yearList: number[] = [];
  year = Number(year);
  for (let index = 0; index < after; index++) {
    yearList.push(year - index);
  }
  return yearList;
};

/**
 * 枚举转转列表
 * @param obj
 * @returns
 */
export const enumConvertList = (obj: any) => {
  let arr = [] as any[];
  for (let key in obj) {
    arr.push({
      label: obj[key],
      value: key,
    });
  }
  return arr;
};

/**
 * 往表头增加公式
 * @param arr 表头
 * @param arr2 公式
 * @returns
 */
export const tableHeadAddFormula = (arr: any[], arr2: any[]) => {
  return arr.map((el: any, idx: number) => {
    let { label, ...other } = el;
    let obj = {
      label: el.label,
      children: [
        {
          label: arr2.length > idx ? arr2[idx] : "",
          ...other,
        },
      ],
    };
    return obj;
  });
};

export const tableHeadAddFormula2 = (arr: any[], arr2: any[]) => {
  return arr.map((el: any, idx: number) => {
    let { label, ...other } = el;
    let obj = {
      label: el.label,
      prop: "p" + idx,
      _children: [
        {
          label: arr2.length > idx ? arr2[idx] : "",
          ...other,
        },
      ],
    };
    return obj;
  });
};

/**
 * 将数组按指定属性分组
 * @param arr
 * @param keyField
 */
export const arrToGroupArr = (arr: any, keyField: string) => {
  let groups = arr.reduce((map: any, obj: any) => {
    let key = obj[keyField];
    if (!map.has(key)) {
      map.set(key, []);
    }
    map.get(key).push(obj);
    return map;
  }, new Map());

  let result = Object.values(groups);
  return result;
};

/**
 * 判断字符串是否是json格式
 * @param str
 * @param emptyNotValid 空值时不校验
 * @returns
 */
export function isJsonString(str: string, emptyNotValid = true) {
  if (!str && emptyNotValid) return true;
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

export async function performMultipleAsyncOperations(asyncTasks: Promise<any>[]): Promise<any[]> {
  try {
    const results: any[] = await Promise.all(asyncTasks);
    return results;
  } catch (error: unknown) {
    throw error; // 或者重新抛出错误以在上层捕获
  }
}
/**
 * 格式化千分位
 * @param num
 * @param keepDecimal 是否保留小数
 * @returns
 */
export function formatToThousandths(num: any, keepDecimal = true, decimalPlaces = 2) {
  // 判断num是否有小数
  if (num === 0) return 0;
  const integerPart = Math.floor(Number(num));
  const decimalPart = keepDecimal ? num - integerPart : 0;

  // 使用toLocaleString()方法处理整数部分的千分位格式化
  const formattedInteger = integerPart.toLocaleString("en-US");

  // 如果需要保留小数点，拼接小数部分
  const formattedNumber =
    keepDecimal && decimalPart !== 0 ? `${formattedInteger}.${decimalPart.toFixed(decimalPlaces).slice(2)}` : formattedInteger;

  return formattedNumber;
}

/**
 * 扁平化数组通过分组转化为树形结构
 * @param arr
 * @param groupName
 */
export function arrByGroupToTree(arr: any[], groupName: string, isHasAll = true) {
  let gorupData = groupBy(arr, groupName);
  let result = [] as any[];
  if (isHasAll) {
    result.push({
      label: "全部",
      value: "undefined",
    });
  }
  for (let key in gorupData) {
    result.push({
      label: key,
      value: key,
      children: gorupData[key],
    });
  }
  return result;
}

/**
 * 表达式和方法使用括号，
 * @param str
 * @returns {boolean}
 */
function isHasExp(str: string) {
  let regex = /\(.*\)/;
  return regex.test(str);
}

/**
 * 将驼峰转化成下划线全大写或转大写
 */
function sqlColumnDeal(str: any, type?: string) {
  switch (type) {
    case "upper":
      return str.toUpperCase();
      break;
    //驼峰转下划线
    case "lineupper":
      return str.replace(/([A-Z])/g, "_$1").toUpperCase();
      break;
    //下划线转驼峰
    case "hump":
      return str.toLowerCase().replace(/_(.)/g, function (match, group1) {
        return group1.toUpperCase();
      });
      break;
    default:
      return str.replace(/([A-Z])/g, "_$1").toUpperCase();
  }
}

export function whereDeal(arr: any) {
  let whereArr = [] as any[];
  if (isType(arr) === "array") {
    arr.forEach((el: any) => {
      if (el && typeof el === "string") {
        let elArr = el.replace(/\s+/g, " ").trim().split(" ");
        if (elArr.length > 0) {
          let temp = {
            column: sqlColumnDeal(elArr[0]), //判断是否包含函数
            operator: elArr[1],
            value: elArr[2] || "",
          } as any;
          if (isHasExp(elArr[0])) {
            temp.type = "SQL";
          }
          if (elArr.length > 3) {
            temp.ogicalOperator = elArr[3].toLowerCase();
          }
          switch (temp.operator) {
            case "like":
              temp.operator = "like";
              temp.value = "%" + temp.value + "%";
              break;
            case "startWith":
              temp.operator = "like";
              temp.value = temp.value + "%";
              break;
            case "endWith":
              temp.operator = "like";
              temp.value = "%" + temp.value;
              break;
            case "!startWith":
              temp.operator = "unlike";
              temp.value = temp.value + "%";
              break;
            case "!endWith":
              temp.operator = "unlike";
              temp.value = "%" + temp.value;
              break;
            case "=":
              temp.operator = "eq";
              break;
            case "!=":
              temp.operator = "ne";
              break;
            case ">":
              temp.operator = "gt";
              break;
            case ">=":
              temp.operator = "ge";
              break;
            case "<":
              temp.operator = "lt";
              break;
            case "<=":
              temp.operator = "le";
              break;
            case "in":
              temp.operator = "in";
              temp.value = temp.value?.split(",");
              break;
            case "!in":
              temp.operator = "notIn";
              temp.value = temp.value?.split(",");
              break;
            case "!like":
              temp.operator = "unlike";
              break;
            case "!between":
              temp.operator = "notBetween";
              break;
            default:
              temp.operator = temp.operator.toLowerCase();
          }
          whereArr.push(temp);
        }
      }
    });
  } else if (isType(arr) === "object") {
    for (let key in arr) {
      whereArr.push({
        column: key,
        value: arr[key],
      });
    }
  }
  return whereArr;
}

/**
 * 子查询
 * @param arr
 * @returns
 */
export function sonWhereDeal(arr: any) {
  let whereArr = whereDeal(arr);
  return whereArr.map((el) => {
    return {
      type: "WHERE",
      where: el,
    };
  });
}
/*
 * 判断当前区划是否为底级
 * @param plateCd 区划编码
 */
export function judgeBottomLevel(plateCd: string) {
  return plateCd && (plateCd == "5300" || plateCd == "530000" || String(plateCd).length === 12);
}

/**
 * 生成一个指定位数得随机数
 * @returns {string}
 */
export function uuid(n = 6) {
  let s = [] as any[];
  let hexDigits = "0123456789abcdef" + new Date().getTime().toString(16);
  for (let i = 0; i < n; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  return s.join("");
}

export function getAmtUnitText(val: number | string) {
  switch (Number(val)) {
    case 1:
      return "元";
      break;
    case 10000:
      return "万元";
      break;
    case 100000000:
      return "亿元";
      break;
    default:
      break;
  }
}

/**
 * 获取系统当前日期和星期
 * @return {Object} {
 *   week 当前星期,
 *   year 当年,
 *   month 当月,
 *   _month 当月双位数,
 *   day 当日,
 *   _day 当日双位数
 * }
 */
interface DateInterface {
  week: string;
  year: number;
  month: number;
  _month: number | string;
  day: number;
  _day: number | string;
  hour: number;
  minutes: number;
  seconds: number;
}
export function getNowDateAndWeek(): DateInterface {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const _month = month < 10 ? "0" + month : month;
  const day = date.getDate();
  const _day = day < 10 ? "0" + day : day;
  const week = date.getDay();
  const hour = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  let nowWeek = "";
  switch (week) {
    case 1:
      nowWeek = "星期一";
      break;
    case 2:
      nowWeek = "星期二";
      break;
    case 3:
      nowWeek = "星期三";
      break;
    case 4:
      nowWeek = "星期四";
      break;
    case 5:
      nowWeek = "星期五";
      break;
    case 6:
      nowWeek = "星期六";
      break;
    case 7:
      nowWeek = "星期天";
      break;
  }
  return {
    week: nowWeek,
    year: year,
    month: month,
    _month: _month,
    day: day,
    _day: _day,
    hour: hour,
    minutes: minutes,
    seconds: seconds,
  };
}

/**
 * 获取当前时间
 * 格式 2024-05-21 12:00
 */
export function getCurrentTime() {
  const res = getNowDateAndWeek();

  return `${res.year}-${res._month}-${res._month} ${res.hour}:${res.minutes}:${res.seconds}`;
}

/**
 * 格式化tooltip
 * @param data {Array<Object>} data 数据
 * @param fields {Array<Object>} 展示字段取值 {
 *     传对象包含五个字段{value: "", style: “”, seriesName: "", name: ""}，解决自定义背景色及背景色不能识别的问题 {
 *         value: 展示值，
 *         style: 样式，自定义css属性背景(background: red)或渐变色background-image: linear-gradient(red,yellow,green)，不传取marker
 *         seriesName: 系列名，必传，用于查找对应关系
 *         name: 自定义name，不传默认取 seriesName
 *         custom: true|false, 是否为自定义图例，默认false
 *     }
 * }
 * @param customName {String} 自定义name
 * @return {string}
 */
interface FormatterFieldsInterface {
  value: string | Function;
  seriesName: string;
  style?: string;
  name?: string;
  custom?: boolean;
}
export function formatterPanel(data: any[], fields: FormatterFieldsInterface[], customName?: string) {
  let panel = "";
  if (Array.isArray(data) && data.length) {
    let name = customName || data[0]["name"];
    panel += `${name}<br/>`;
    fields.forEach((opt) => {
      if (opt) {
        const series = data.find((ele) => {
          return ele["seriesName"] === opt["seriesName"];
        });
        if (series) {
          if (opt.style) {
            if (series.seriesType === "line") {
              panel += `<span style="position:relative;bottom: 4px;left: -1px;display:inline-block;margin-right:4px;width:15px;height:2px;${opt.style};"></span>`;
            } else {
              panel += `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;${opt.style};"></span>`;
            }
          } else {
            if (series.seriesType === "line") {
              const dom = document.createElement("div");
              dom.innerHTML = series["marker"];
              let background = (dom.firstChild as HTMLDivElement).style.backgroundColor;
              panel += `<span style="position:relative;bottom: 4px;left: -1px;display:inline-block;margin-right:4px;width:15px;height:2px;background-color:${background};"></span>`;
            } else {
              panel += series["marker"];
            }
          }
          panel += `${opt.name || series["seriesName"]}: ${
            typeof opt["value"] === "function" ? opt["value"](series) : opt["value"]
          }<br/>`;
        } else {
          if (opt.custom) {
            panel += `${opt.name}:${typeof opt["value"] === "function" ? opt["value"](series) : opt["value"]}<br/>`;
          }
        }
      }
    });
  }
  return panel;
}

/**
 * @description 处理 prop，当 prop 为多级嵌套时 ==> 返回最后一级 prop
 * @param {String} prop 当前 prop
 * @returns {String}
 * */
export function handleProp(prop: string) {
  const propArr = prop.split(".");
  if (propArr.length == 1) return prop;
  return propArr[propArr.length - 1];
}

/**
 * @description 根据枚举列表查询当需要的数据（如果指定了 label 和 value 的 key值，会自动识别格式化）
 * @param {String} callValue 当前单元格值
 * @param {Array} enumData 字典列表
 * @param {Array} fieldNames label && value && children 的 key 值   FieldNamesProps
 * @param {String} type 过滤类型（目前只有 tag）
 * @returns {String}
 * */
export function filterEnum(callValue: any, enumData?: any, fieldNames?: any, type?: "tag") {
  const value = fieldNames?.value ?? "value";
  const label = fieldNames?.label ?? "label";
  const children = fieldNames?.children ?? "children";
  let filterData: { [key: string]: any } = {};
  // 判断 enumData 是否为数组
  if (Array.isArray(enumData)) filterData = findItemNested(enumData, callValue, value, children);
  // 判断是否输出的结果为 tag 类型
  if (type == "tag") {
    return filterData?.tagType ? filterData.tagType : "";
  } else {
    return filterData ? filterData[label] : "";
  }
}

/**
 * @description 递归查找 callValue 对应的 enum 值
 * */
export function findItemNested(enumData: any, callValue: any, value: string, children: string) {
  return enumData.reduce((accumulator: any, current: any) => {
    if (accumulator) return accumulator;
    if (current[value] === callValue) return current;
    if (current[children]) return findItemNested(current[children], callValue, value, children);
  }, null);
}

/**
 * @description 处理 ProTable 值为数组 || 无数据
 * @param {*} callValue 需要处理的值
 * @returns {String}
 * */
export function formatValue(callValue: any) {
  // 如果当前值为数组，使用 / 拼接（根据需求自定义）
  if (isType(callValue) === "array") return callValue.length ? callValue.join(" / ") : "";
  return callValue ?? "";
}

/**
 * @description 处理 prop 为多级嵌套的情况，返回的数据 (列如: prop: user.name)
 * @param {Object} row 当前行数据
 * @param {String} prop 当前 prop
 * @returns {*}
 * */
export function handleRowAccordingToProp(row: { [key: string]: any }, prop: string) {
  if (!prop.includes(".")) return row[prop] ?? "";
  prop.split(".").forEach((item) => (row = row[item] ?? ""));
  return row;
}

/**
 * 获取url路径和参数
 * @param url
 * @returns
 */
export function getUrlParams(url: string) {
  let arr = url.split("?");
  let returnObj = {
    path: "",
    query: {} as any,
  };
  let len = arr.length;
  if (len > 0) {
    returnObj.path = arr[0];
    if (len > 1) {
      let queryArr = arr[1].split("&");
      for (let i = 0; i < queryArr.length; i++) {
        let pair = queryArr[i].split("=");
        returnObj.query[pair[0]] = decodeURIComponent(pair[1]);
      }
    }
  }
  return returnObj;
}

// base64 转 blob
export function base64ToBlob(content: string) {
  let parts = content.split(";base64,");
  let contentType = parts[0].split(":")[1];
  let raw = window.atob(parts[1]);
  let rawLength = raw.length;
  let uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
}

// 获取进度条中间进度图形格数
export function getProcessIcon(num: Number | string, num1: Number | string) {
  let total = 21; // 满格格数 TODO：可以根据中间的元素宽度，动态计算，现暂定21.后面可根据能力优化
  if (num && num1) {
    let icon = Math.floor((Number(num) / Number(num1)) * total);
    if (icon >= total) {
      icon = total;
    }
    return icon;
  } else {
    return 0;
  }
}

/**
 * 根据字数长度，变化字体大小，返回字体大小,每增加一个字符，字体减少对应像素
 * @params str: 字符串或数字
 * @params fontMax: 字体最大值
 * @params fontMin: 字体最小值
 * @params maxLen: 允许原样大小的最大长度
 * @params step: 字体大小变化级次长度
 * @params str: 字符串或数字
 */
export function getFontSize(
  str: number | string,
  fontMax: number = 20,
  fontMin: number = 8,
  maxLen: number = 10,
  step: number = 1,
) {
  if (str) {
    let fontSize = fontMax;
    let length = String(str).length;
    if (length <= maxLen) {
      fontSize = fontMax;
    } else {
      let dec = length - maxLen;
      let decFont = fontMax - dec * step;
      if (decFont < fontMin) {
        fontSize = fontMin;
      } else {
        fontSize = decFont;
      }
      return fontSize + "px";
    }
  } else {
    return fontMax + "px";
  }
}
